angular.module('app.services', [])
    .config(["$httpProvider", function($httpProvider) {　　
        $httpProvider.interceptors.push("httpInterceptor");
    }])
    .value("sidebarMenu", [{
            id: 0,
            title: "管理首页",
            icon: "icon-home",
            url: "/home.html",
        }, {
            id: 1,
            title: "系统管理",
            icon: "icon-wrench",
            tagname: [12, 13, 11],
            subMenu: [{
                id: 11,
                title: "用户管理",
                icon: "icon-user",
                url: "/GgcmsUsersList.html"
            }, {
                id: 12,
                title: "企业管理",
                icon: "icon-star",
                url: "/GgcmsCompanyList.html"
            }, {
                id: 13,
                title: "答题用户组",
                icon: "icon-notebook",
                url: "/GgcmsSysdictsList.html?group=UserGroup",
            }, {
                id: 14,
                title: "消息管理",
                icon: "icon-envelope",
                url: "/GgcmsMessagesList.html"
            }, ]
        },
        {
            id: 2,
            title: "导航菜单设置",
            icon: "icon-directions",
            tagname: [21, 22, 23, 24],
            subMenu: [{
                id: 21,
                title: "管理部门导航",
                icon: "icon-magic-wand",
                url: "/GgcmsCategoryList.html?userType=1"
            }, {
                id: 22,
                title: "企业管理员",
                icon: "icon-magnet",
                url: "/GgcmsCategoryList.html?userType=2",
                hide: true
            }, {
                id: 23,
                title: "企业管理员",
                icon: "icon-plane",
                url: "/GgcmsCategoryList.html?userType=3",
                hide: true
            }, {
                id: 24,
                title: "普通用户导航",
                icon: "icon-badge",
                url: "/GgcmsCategoryList.html?userType=4"
            }]
        },
        {
            id: 3,
            title: "内容管理",
            icon: "icon-book-open",
            tagname: [31, 32],
            subMenu: [{
                id: 31,
                title: "内容分类管理",
                icon: "icon-layers",
                url: "/GgcmsCategoryList.html?userType=0"
            }, {
                id: 32,
                title: "文章管理",
                icon: "icon-docs",
                url: "/GgcmsArticleList.html"
            }, ]
        },
        {
            id: 4,
            title: "教程管理",
            icon: "icon-graduation",
            tagname: [41, 42, 43, 44],
            subMenu: [{
                id: 41,
                title: "教程分类",
                icon: "icon-grid",
                url: "/GgcmsCategoryList.html?userType=99",
                hide: true
            }, {
                id: 42,
                title: "教程管理",
                icon: "icon-vector",
                url: "/GgcmsTutorialList.html"
            }, {
                id: 43,
                title: "试题管理",
                icon: "icon-question",
                url: "/GgcmsQuestionsList.html"
            }, {
                id: 44,
                title: "教程评价",
                icon: "icon-star",
                url: "/GgcmsAssessList.html"
            }, ]
        },
        {
            id: 5,
            title: "辅助管理",
            icon: "icon-settings",
            tagname: [53, 51, 52],
            subMenu: [{
                id: 51,
                title: "广告管理",
                icon: "icon-target",
                url: "/GgcmsAdsList.html"
            }, {
                id: 52,
                title: "答题记录",
                icon: "glyphicon glyphicon-list",
                url: "/GgcmsExamRecordList.html"
            }, {
                id: 53,
                title: "学习记录",
                icon: "glyphicon glyphicon-tasks",
                url: "/GgcmsLearnRecordList.html"
            }, ]
        },
    ])
    .factory("appHandle", function() {
        var handleUniform = function() {
            if (!$().uniform) {
                return;
            }
            var test = $("input[type=checkbox]:not(.toggle, .md-check, .md-radiobtn, .make-switch, .icheck), input[type=radio]:not(.toggle, .md-check, .md-radiobtn, .star, .make-switch, .icheck)");
            if (test.size() > 0) {
                test.each(function() {
                    // if ($(this).parents(".checker").size() === 0) {
                    //     $(this).show();
                    // }
                    $(this).uniform();
                });
            }
        };
        // Handles the horizontal menu
        var handleHeader = function() {
            // handle search box expand/collapse        
            $('.page-header').on('click', '.search-form', function(e) {
                $(this).addClass("open");
                $(this).find('.form-control').focus();

                $('.page-header .search-form .form-control').on('blur', function(e) {
                    $(this).closest('.search-form').removeClass("open");
                    $(this).unbind("blur");
                });
            });

            // handle hor menu search form on enter press
            $('.page-header').on('keypress', '.hor-menu .search-form .form-control', function(e) {
                if (e.which == 13) {
                    $(this).closest('.search-form').submit();
                    return false;
                }
            });

            // handle header search button click
            $('.page-header').on('mousedown', '.search-form.open .submit', function(e) {
                e.preventDefault();
                e.stopPropagation();
                $(this).closest('.search-form').submit();
            });
        };

        return {
            initComponents: function() {
                handleUniform();
            },
            initHeader: function() {
                handleHeader();
            },
            initSidebar: function() {

            },
            initFooter: function() {

            }
        };
    })
    .factory("httpInterceptor", ["$q", "$rootScope", function($q, $rootScope) {
        var msgShow = function(msg) {
            $.blockUI({
                message: "<h1>" + msg + "</h1>",
                timeout: 1000,
                css: {
                    border: 'none',
                    padding: '15px',
                    backgroundColor: '#000',
                    '-webkit-border-radius': '10px',
                    '-moz-border-radius': '10px',
                    opacity: .8,
                    color: '#fff'
                },
            });
        };
        return {
            request: function(config) {
                // do something on request success
                return config || $q.when(config);
            },
            requestError: function(rejection) {　　　　 // do something on request error
                return $q.reject(rejection)　　
            },
            response: function(response) {
                // do something on response success
                if (response.data.Code == 3) {
                    msgShow(msg);
                    return null;
                }
                return response || $q.when(response);
            },
            responseError: function(rejection) {
                console.log(rejection);
                msgShow(rejection.data.Message);
                // do something on response error
                return $q.reject(rejection);
            }
        };
    }])
    .factory("dataApi", function($rootScope, $http, Tools, localStorageService) {
        console.log("dataApi");
        var static_dir = sysConfigs.sdir;
        return {
            getDicts: function() {
                var url = static_dir + '/data/dicts.json?rnd=' + Tools.timeStamp();
                return $http.get(url)
                    .then(function(response) {
                        var data = response.data;
                        return data;
                    });
            },
            getAddress: function() {
                var url = static_dir + '/data/address.json?rnd=' + Tools.timeStamp();
                return $http.get(url)
                    .then(function(response) {
                        var data = response.data;
                        return data;
                    });
            },
            loginSubmit: function(data) {
                var url = '/api/Login/PostLogin?rnd=' + Tools.timeStamp();
                return $http.post(url, data)
                    .then(function(response) {
                        var data = response.data;
                        return data;
                    });
            },
            logout: function() {
                var url = '/api/Login/GetLogout?rnd=' + Tools.timeStamp();
                return $http.get(url)
                    .then(function(response) {
                        var data = response.data;
                        return data;
                    });
            },
            GgcmsAdsList: function(pageData) {
                var self = this;
                var url = '/admin/GgcmsAds';
                return $http.get(url, { params: pageData })
                    .then(function(response) {
                        var data = response.data;
                        return data;
                    });
            },
            GgcmsAdsListDelete: function(ids) {
                var url = '/admin/GgcmsAds/delete';
                return $http.post(url, ids)
                    .then(function(response) {
                        var data = response.data;
                        return data;
                    });
            },
            GgcmsAdsAdd: function(data) {
                var upType = "add";
                if (data.Id > 0) {
                    upType = "edit";
                }
                var url = '/admin/GgcmsAds/' + upType;
                return $http.post(url + "?rnd=" + Tools.timeStamp(), data)
                    .then(function(response) {
                        var data = response.data;
                        return data;
                    });
            },
            GgcmsAdsAddGetInfo: function(id) {
                var url = '/admin/GgcmsAds/' + id;
                return $http.get(url, { params: { rnd: Tools.timeStamp() } })
                    .then(function(response) {
                        var data = response.data;
                        return data;
                    });
            },
            GgcmsAssessList: function(pageData) {
                var self = this;
                var url = '/admin/GgcmsAssess';
                if (!pageData.sortby) {
                    pageData.sortby = "Id";
                    pageData.order = "desc";
                }
                return $http.get(url, { params: pageData })
                    .then(function(response) {
                        var data = response.data;
                        return data;
                    });
            },
            GgcmsAssessListDelete: function(ids) {
                var url = '/admin/GgcmsAssess/delete';
                return $http.post(url, ids)
                    .then(function(response) {
                        var data = response.data;
                        return data;
                    });
            },
            GgcmsArticleList: function(pageData) {
                var url = '/api/GgcmsArticles/GetList';
                if (!pageData.fields) {
                    pageData.fields = "Id,Title,Category_Id,CreateTime,TitleImg,Description,ShowType,ShowLevel,Keywords,Author,Source,SourceUrl";
                }
                if (!pageData.sortby) {
                    pageData.sortby = "Id";
                    pageData.order = "desc";
                }
                var self = this;
                return $http.get(url, { params: pageData })
                    .then(function(response) {
                        var data = response.data;
                        return data;
                    });
            },
            GgcmsArticleListDelete: function(ids) {
                var url = '/api/GgcmsArticles/delete';
                return $http.post(url, ids)
                    .then(function(response) {
                        var data = response.data;
                        return data;
                    });
            },
            GgcmsArticleAdd: function(data) {
                var upType = "add";
                if (data.Id > 0) {
                    upType = "edit";
                }
                var udata = angular.copy(data);
                if (angular.isObject(udata.Companyid)) {
                    udata.Companyid = udata.Companyid.Id;
                }
                var url = '/api/GgcmsArticles/' + upType;
                return $http.post(url + "?rnd=" + Tools.timeStamp(), udata)
                    .then(function(response) {
                        var data = response.data;
                        return data;
                    });
            },
            GgcmsArticleAddGetInfo: function(id) {
                var url = '/api/GgcmsArticles/' + id;
                return $http.get(url, { params: { rnd: Tools.timeStamp() } })
                    .then(function(response) {
                        var data = response.data;
                        return data;
                    });
            },
            GgcmsCategoryList: function(pageData) {
                var url = '/api/GgcmsCategories/GetList';
                return $http.get(url, { params: pageData })
                    .then(function(response) {
                        var data = response.data;
                        return data;
                    });
            },
            GgcmsCategorySaveSort: function(list) {
                var url = '/api/GgcmsCategories/savesort' + "?rnd=" + Tools.timeStamp();
                return $http.post(url, list)
                    .then(function(response) {
                        var data = response.data;
                        return data;
                    });
            },
            GgcmsCategoryListDelete: function(ids) {
                var url = '/api/GgcmsCategories/delete';
                return $http.post(url, ids)
                    .then(function(response) {
                        var data = response.data;
                        return data;
                    });
            },
            GgcmsCategoryAdd: function(data) {
                var upType = "add";
                if (data.Id > 0) {
                    upType = "edit";
                }
                var udata = angular.copy(data);
                if (angular.isString(udata.Companyid)) {
                    udata.Companyid = parseInt(udata.Companyid);
                    udata.Companyid = udata.Companyid || 0;
                }
                var url = '/api/GgcmsCategories/' + upType;
                return $http.post(url + "?rnd=" + Tools.timeStamp(), udata)
                    .then(function(response) {
                        return response.data;
                    });
            },
            GgcmsCategoryAddGetInfo: function(id) {
                var url = '/api/GgcmsCategories/GetInfo/' + id;
                return $http.get(url, { params: { rnd: Tools.timeStamp() } })
                    .then(function(response) {
                        var data = response.data;
                        return data;
                    });
            },
            GgcmsCompanyList: function(pageData) {
                var url = '/admin/GgcmsCompany';
                if (!pageData.fields) {
                    pageData.fields = "Id,Cname,Address,Phone,Contacts";
                }
                return $http.get(url, { params: pageData })
                    .then(function(response) {
                        var data = response.data;
                        return data;
                    });
            },
            GgcmsCompanyListDelete: function(ids) {
                var url = '/admin/GgcmsCompany/delete';
                return $http.post(url, ids)
                    .then(function(response) {
                        var data = response.data;
                        return data;
                    });
            },
            GgcmsCompanyAdd: function(data) {
                var upType = "add";
                if (data.Id > 0) {
                    upType = "edit";
                }
                var url = '/admin/GgcmsCompany/' + upType;
                return $http.post(url + "?rnd=" + Tools.timeStamp(), data)
                    .then(function(response) {
                        var data = response.data;
                        return data;
                    });
            },
            GgcmsCompanyAddGetInfo: function(id) {
                var url = '/admin/GgcmsCompany/' + id;
                return $http.get(url, { params: { rnd: Tools.timeStamp() } })
                    .then(function(response) {
                        var data = response.data;
                        return data;
                    });
            },
            GgcmsExamRecordList: function(pageData) {
                var url = '/admin/GgcmsExamRecord';
                return $http.get(url, { params: pageData })
                    .then(function(response) {
                        var data = response.data;
                        return data;
                    });
            },
            GgcmsExamRecordListDelete: function(ids) {
                var url = '/admin/GgcmsExamRecord/delete';
                return $http.post(url, ids)
                    .then(function(response) {
                        var data = response.data;
                        return data;
                    });
            },
            GgcmsExamRecordAdd: function(data) {
                var upType = "add";
                if (data.Id > 0) {
                    upType = "edit";
                }
                var url = '/admin/GgcmsExamRecord/' + upType;
                return $http.post(url + "?rnd=" + Tools.timeStamp(), data)
                    .then(function(response) {
                        var data = response.data;
                        return data;
                    });
            },
            GgcmsExamRecordAddGetInfo: function(id) {
                var url = '/admin/GgcmsExamRecord/' + id;
                return $http.get(url, { params: { rnd: Tools.timeStamp() } })
                    .then(function(response) {
                        var data = response.data;
                        return data;
                    });
            },
            GgcmsLearnRecordList: function(pageData) {
                var url = '/admin/GgcmsLearnRecord';
                return $http.get(url, { params: pageData })
                    .then(function(response) {
                        var data = response.data;
                        return data;
                    });
            },
            GgcmsLearnRecordListDelete: function(ids) {
                var url = '/admin/GgcmsLearnRecord/delete';
                return $http.post(url, ids)
                    .then(function(response) {
                        var data = response.data;
                        return data;
                    });
            },
            GgcmsLearnRecordAdd: function(data) {
                var upType = "add";
                if (data.Id > 0) {
                    upType = "edit";
                }
                var url = '/admin/GgcmsLearnRecord/' + upType;
                return $http.post(url + "?rnd=" + Tools.timeStamp(), data)
                    .then(function(response) {
                        var data = response.data;
                        return data;
                    });
            },
            GgcmsLearnRecordAddGetInfo: function(id) {
                var url = '/admin/GgcmsLearnRecord/' + id;
                return $http.get(url, { params: { rnd: Tools.timeStamp() } })
                    .then(function(response) {
                        var data = response.data;
                        return data;
                    });
            },
            GgcmsQuestionsList: function(pageData) {
                if (!pageData.fields) {
                    pageData.fields = "Id,Title,Cdate,Qtype,Answer";
                }
                if (!pageData.sortby) {
                    pageData.sortby = "Id";
                    pageData.order = "desc";
                }
                var url = '/admin/GgcmsQuestions';
                return $http.get(url, { params: pageData })
                    .then(function(response) {
                        var data = response.data;
                        return data;
                    });
            },
            GetQuestionsList: function(pageData) {
                if (!pageData.fields) {
                    pageData.fields = "Id,Title,Cdate,Qtype,Answer";
                }
                if (!pageData.sortby) {
                    pageData.sortby = "Id";
                    pageData.order = "desc";
                }
                var url = '/admin/GgcmsQuestions/list';
                return $http.get(url, { params: pageData })
                    .then(function(response) {
                        var data = response.data;
                        return data;
                    });
            },
            GgcmsQuestionsListDelete: function(ids) {
                var url = '/admin/GgcmsQuestions/delete';
                return $http.post(url, ids)
                    .then(function(response) {
                        var data = response.data;
                        return data;
                    });
            },
            GgcmsQuestionsAdd: function(data) {
                var upType = "add";
                if (data.Id > 0) {
                    upType = "edit";
                }
                var url = '/admin/GgcmsQuestions/' + upType;
                return $http.post(url + "?rnd=" + Tools.timeStamp(), data)
                    .then(function(response) {
                        var data = response.data;
                        return data;
                    });
            },
            GgcmsQuestionsAddGetInfo: function(id) {
                var url = '/admin/GgcmsQuestions/' + id;
                return $http.get(url, { params: { rnd: Tools.timeStamp() } })
                    .then(function(response) {
                        var data = response.data;
                        return data;
                    });
            },
            getSysDicts: function(group, reload) {
                var sname = "sysdict-" + group;
                var sdata = localStorageService.get(sname);
                if (reload || !sdata) {
                    var pageData = {
                        limit: 1000,
                        offset: 0,
                        pagenum: 1,
                        query: "dgroup:UserGroup",
                        sortby: "sortid",
                        order: "asc",
                        fields: "Id,Dkey",
                        rnd: Tools.timeStamp(),
                    };
                    return this.GgcmsSysdictsList(pageData).then(function(data) {
                        localStorageService.update(sname, data.Data.List);
                        return data.Data.List;
                    });
                } else {
                    return new Promise(function(resolve, reject) {
                        if (sdata) {
                            resolve(sdata);
                        } else {
                            reject(null);
                        }
                    });
                }
            },
            GgcmsSysdictsList: function(pageData) {
                var url = '/api/GgcmsDictionaries/GetGgcmsDictionaries';
                return $http.get(url, { params: pageData })
                    .then(function(response) {
                        var data = response.data;
                        return data;
                    });
            },
            GgcmsSysdictsListDelete: function(ids) {
                var url = '/admin/GgcmsSysdicts/delete';
                return $http.post(url, ids)
                    .then(function(response) {
                        var data = response.data;
                        return data;
                    });
            },
            GgcmsSysdictsAdd: function(data) {
                var upType = "add";
                if (data.Id > 0) {
                    upType = "edit";
                }
                var url = '/admin/GgcmsSysdicts/' + upType;
                return $http.post(url + "?rnd=" + Tools.timeStamp(), data)
                    .then(function(response) {
                        var data = response.data;
                        return data;
                    });
            },
            GgcmsSysdictsAddGetInfo: function(id) {
                var url = '/admin/GgcmsSysdicts/' + id;
                return $http.get(url, { params: { rnd: Tools.timeStamp() } })
                    .then(function(response) {
                        var data = response.data;
                        return data;
                    });
            },
            GgcmsTutorialList: function(pageData) {
                var url = '/admin/GgcmsTutorial';
                if (!pageData.fields) {
                    pageData.fields = "Id,Title,Description,Thumbnail,Playcount,Cdate,Datekey";
                }
                if (!pageData.sortby) {
                    pageData.sortby = "Id";
                    pageData.order = "desc";
                }
                var self = this;
                return $http.get(url, { params: pageData })
                    .then(function(response) {
                        var data = response.data;
                        return data;
                    });
            },
            GetTutorialList: function(pageData) {
                //带分组，查视图
                var url = '/admin/GgcmsTutorial/list';
                if (!pageData.fields) {
                    pageData.fields = "Id,Title,Description,Thumbnail,Playcount,Cdate,Datekey";
                }
                if (!pageData.sortby) {
                    pageData.sortby = "Id";
                    pageData.order = "desc";
                }
                var self = this;
                return $http.get(url, { params: pageData })
                    .then(function(response) {
                        var data = response.data;
                        return data;
                    });
            },
            GgcmsTutorialListDelete: function(ids) {
                var url = '/admin/GgcmsTutorial/delete';
                return $http.post(url, ids)
                    .then(function(response) {
                        var data = response.data;
                        return data;
                    });
            },
            GgcmsTutorialAdd: function(data) {
                var upType = "add";
                if (data.Id > 0) {
                    upType = "edit";
                }
                var udata = angular.copy(data);
                if (angular.isObject(udata.Companyid)) {
                    udata.Companyid = udata.Companyid.Id;
                }
                var url = '/admin/GgcmsTutorial/' + upType;
                return $http.post(url + "?rnd=" + Tools.timeStamp(), udata)
                    .then(function(response) {
                        var data = response.data;
                        return data;
                    });
            },
            GgcmsTutorialAddGetInfo: function(id) {
                var url = '/admin/GgcmsTutorial/' + id;
                return $http.get(url, { params: { rnd: Tools.timeStamp() } })
                    .then(function(response) {
                        var data = response.data;
                        return data;
                    });
            },
            fillCompanyName: function(data) {
                var comids = [];
                if (!data.List || data.List.length == 0) {
                    return;
                }
                data.List.forEach(function(item) {
                    if (item.Companyid > 0 && comids.indexOf(item.Companyid) == -1) {
                        comids.push(item.Companyid);
                    }
                }, this);
                if (comids.length == 0) {
                    return;
                }
                var comPageData = {
                    limit: 100,
                    offset: 0,
                    pagenum: 1,
                    fields: "Cname,Id",
                    query: "Id.in:" + comids.join("|"),
                    rnd: Tools.timeStamp(),
                };
                this.GgcmsCompanyList(comPageData).then(
                    function(compdata) {
                        if (compdata.Code == 0 && compdata.Data.Count > 0) {
                            data.List.forEach(function(item) {
                                if (item.Companyid > 0) {
                                    compdata.Data.List.forEach(function(comp) {
                                        if (comp.Id == item.Companyid) {
                                            item.CompanyName = comp.Cname;
                                            return;
                                        }
                                    }, this);
                                } else {
                                    item.CompanyName = "";
                                }
                            }, this);
                        }
                    }
                );
            },
            GgcmsUsersList: function(pageData) {
                var url = '/api/GgcmsMembers/GetGgcmsMembers';
                var self = this;
                if (!pageData.fields) {
                    pageData.fields = "Id,Userid,Usertype,UserGroup,Realname,Companyid,Status";
                }
                return $http.get(url, { params: pageData })
                    .then(function(response) {
                        var data = response.data;
                        self.fillCompanyName(data.Data);
                        return data;
                    });
            },
            GgcmsUsersListDelete: function(ids) {
                var url = '/admin/GgcmsUsers/delete';
                return $http.post(url, ids)
                    .then(function(response) {
                        var data = response.data;
                        return data;
                    });
            },
            GgcmsUsersAdd: function(data) {
                var upType = "add";
                if (data.Id > 0) {
                    upType = "edit";
                }
                var udata = angular.copy(data);
                if (angular.isObject(udata.Companyid)) {
                    udata.Companyid = udata.Companyid.Id;
                }
                udata.Sex = parseInt(data.Sex);
                var url = '/admin/GgcmsUsers/' + upType;
                return $http.post(url + "?rnd=" + Tools.timeStamp(), udata)
                    .then(function(response) {
                        var data = response.data;
                        return data;
                    });
            },
            GgcmsUsersAddGetInfo: function(id) {
                var url = '/admin/GgcmsUsers/' + id;
                return $http.get(url, { params: { rnd: Tools.timeStamp() } })
                    .then(function(response) {
                        var data = response.data;
                        return data;
                    });
            },
            GgcmsMessagesList: function(pageData) {
                var url = '/admin/GgcmsMessages';
                return $http.get(url, { params: pageData })
                    .then(function(response) {
                        var data = response.data;
                        return data;
                    });
            },
            GgcmsMessagesListDelete: function(ids) {
                var url = '/admin/GgcmsMessages/delete';
                return $http.post(url, ids)
                    .then(function(response) {
                        var data = response.data;
                        return data;
                    });
            },
            GgcmsMessagesAdd: function(data) {
                var upType = "add";
                if (data.Id > 0) {
                    upType = "edit";
                }
                var url = '/admin/GgcmsMessages/' + upType;
                return $http.post(url + "?rnd=" + Tools.timeStamp(), data)
                    .then(function(response) {
                        var data = response.data;
                        return data;
                    });
            },
            GgcmsMessagesAddGetInfo: function(id) {
                var url = '/admin/GgcmsMessages/' + id;
                return $http.get(url, { params: { rnd: Tools.timeStamp() } })
                    .then(function(response) {
                        var data = response.data;
                        return data;
                    });
            },
        }
    })
    .factory("Tools", function($uibModal, $timeout) {
        var staic_root = sysConfigs.cfg_prefixpath;
        var btnOption = {
            closeModal: true,
            className: "btn-lg btn-info",
        }
        var alertOption = {
            icon: "info",
            backdrop: false,
        };
        var loadingOption = {
            zIndex: 10050,
            message: "<h1>请稍候...</h1>",
            timeout: 0,
            css: {
                border: 'none',
                padding: '15px',
                backgroundColor: '#000',
                '-webkit-border-radius': '10px',
                '-moz-border-radius': '10px',
                opacity: .8,
                color: '#fff'
            }
        };

        return {
            alert: function(option) {
                if (angular.isString(option)) {
                    option = {
                        title: option,
                    };
                }
                var defaultOption = angular.copy(alertOption);
                if (option) {
                    option = angular.extend(defaultOption, option);
                } else {
                    option = defaultOption;
                }
                if (option.buttons) {
                    for (var i in option.buttons) {
                        var bopt = angular.copy(btnOption);
                        bopt = angular.extend(bopt, option.buttons[i]);
                        option.buttons[i] = bopt;
                    };
                } else {
                    var bopt = angular.copy(btnOption);
                    bopt.name = "确定";
                    option.buttons = [bopt];
                }
                var tmpl = "<div class=\'gs-alert  showGsAlert visible\' tabindex=\'-1\' data-custom-class=\'\' data-has-cancel-button=\'false\' data-has-confirm-button=\'true\' data-allow-outside-click=\'true\' data-has-done-function=\'true\' data-animation=\'pop\' data-timer=\'null\' style=\'display: block;\'><div class=\'sa-icon sa-error animateErrorIcon\' ng-show=\"option.icon=='error'\">" +
                    "      <span class=\'sa-x-mark\'>" +
                    "        <span class=\'sa-line sa-left\'></span>" +
                    "        <span class=\'sa-line sa-right\'></span>" +
                    "      </span>" +
                    "    </div><div class=\'sa-icon sa-warning animateErrorIcon\' ng-show=\"option.icon=='warning'\">" +
                    "      <span class=\'sa-body pulseWarningIns\'></span>" +
                    "      <span class=\'sa-dot pulseWarningIns\'></span>" +
                    "    </div><div class=\'sa-icon sa-info animateErrorIcon\' ng-show=\"option.icon=='info'\"></div><div class=\'sa-icon sa-success animateErrorIcon\'  ng-show=\"option.icon=='success'\">" +
                    "      <span class=\'sa-line sa-tip\'></span>" +
                    "      <span class=\'sa-line sa-long\'></span>" +
                    "      <div class=\'sa-placeholder\'></div>" +
                    "      <div class=\'sa-fix\'></div>" +
                    "    </div><div class=\'sa-question fa fa-question-circle animateErrorIcon\' ng-show=\"option.icon=='question'\"></div>" +
                    "   <div class=\'sa-icon sa-custom {{option.customicon}}\'  ng-show=\"option.icon=='custom'\"></div><h2 ng-bind-html=\"option.title\"></h2>" +
                    "    <p class=\'lead text-muted \' ng-bind-html=\"option.content\" ng-if=\"option.content\"></p>" +
                    "    <div class=\'form-group\'>" +
                    "      <input type=\'text\' class=\'form-control\' tabindex=\'3\' placeholder=\'\'>" +
                    "      <span class=\'sa-input-error help-block\'>" +
                    "        <span class=\'glyphicon glyphicon-exclamation-sign\'></span> <span class=\'sa-help-text\'>Not valid</span> </span>" +
                    "    </div><div class=\'sa-button-container\'>" +
                    "      <ng-repeat ng-repeat='btn in option.buttons'>" +
                    "      <button ng-click=\"btnClick(btn)\" class=\'btn {{btn.className}}\'>{{btn.name}}</button>" +
                    "      </ng-repeat>" +
                    "    </div></div>";
                var modalInstance = $uibModal.open({
                    animation: true,
                    backdrop: option.backdrop,
                    windowClass: option.backdrop ? null : "gs-overlay",
                    ariaLabelledBy: 'modal-title-bottom',
                    ariaDescribedBy: 'modal-body-bottom',
                    template: tmpl,
                    controller: function($scope, $uibModalInstance) {
                        $scope.option = option;
                        $scope.btnClick = function(btn) {
                            if (btn.click) {
                                btn.click();
                            }
                            if (btn.closeModal) {
                                $uibModalInstance.close(btn);
                            }
                        };
                    }
                });
                modalInstance.result.then(function(data) {

                }, function() {

                });
            },
            loading: function(option, time_out) {
                if (angular.isString(option)) {
                    option = {
                        message: option,
                    };
                }
                if (time_out && angular.isNumber(time_out)) {
                    option.timeout = time_out;
                }
                var defaultOption = angular.copy(loadingOption);
                if (option) {
                    option = angular.extend(defaultOption, option);
                } else {
                    option = defaultOption;
                }
                option.css["z-index"] = option.zIndex;
                $.blockUI(option);
            },
            removeLoading: function() {
                $.unblockUI();
            },
            timeStamp: function() {
                return ((new Date()).getTime());
            },
            dateFormat: function(val, fmt) {
                fmt = fmt || "yyyy-MM-dd";
                val = new Date(val);
                try {
                    var o = {
                        "M+": val.getMonth() + 1, //月份 
                        "d+": val.getDate(), //日 
                        "h+": val.getHours(), //小时 
                        "m+": val.getMinutes(), //分 
                        "s+": val.getSeconds(), //秒 
                        "q+": Math.floor((val.getMonth() + 3) / 3), //季度 
                        "S": val.getMilliseconds() //毫秒 
                    };
                    if (/(y+)/.test(fmt))
                        fmt = fmt.replace(RegExp.$1, (val.getFullYear() + "").substr(4 - RegExp.$1.length));
                    for (var k in o)
                        if (new RegExp("(" + k + ")").test(fmt))
                            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
                    return fmt;
                } catch (e) {
                    console.log('Format date error：' + e.message);
                }
            },
            dateExpress: function(str, val) {
                var d = new Date();
                //以当前值为标准
                if (/v$/.test(str) && val) {
                    d = new Date(val);
                    str = str.replace(/v$/, "");
                }
                if (/c$/.test(str)) {
                    str = str.replace(/c$/, "");
                    var dd = str.split(/[,;:|]/);
                    if (dd.length == 2) {
                        d = new Date(dd[0]);
                        str = dd[1];
                    }
                }
                //或取增减天数
                var v = parseInt(str);
                //月
                if (/m$/.test(str)) {
                    return d.setMonth(d.getMonth() + v);
                }
                //年
                if (/y$/.test(str)) {
                    return d.setFullYear(d.getFullYear() + v);
                }
                //天
                if (/d$/.test(str)) {
                    return d.setDate(d.getDate() + v);
                }
                return Date.parse(d);
            },
            stringToInputItem: function(item) {
                //文件
                if (item.opts.type == "file") {
                    item.FileValue = item.Value;
                }
                //日期转换
                if (item.opts.type == "date" || item.opts.type == "datetime") {
                    item.Value = Date.parse(item.Value);
                }
                //数字转换
                if (item.opts.type == "number") {
                    if (item.Value.indexOf(".") == -1) {
                        item.Value = parseInt(item.Value) || "0";
                    } else {
                        item.Value = parseFloat(item.Value) || "0";
                    }
                }
                //多选转为数组
                if (item.opts.type == "select" && item.opts.multiple) {
                    item.Value = item.Value.split(",");
                }
                return item;
            },
        }
    })
    .factory("listSvr", function($state, $timeout, dataApi, Tools, appHandle) {
        var $scope = {};
        var self = this;
        return {
            init: function(scope) {
                self.$scope = scope;
            },
            listDataLoad: function(pn, qs) {
                var stateName = self.$scope.currentInfo.listSvrName || $state.current.name;
                pn = pn || 1;
                self.$scope.currentInfo.checkBoxAll = false;
                if (dataApi[stateName]) {
                    var pageData = {
                        limit: self.$scope.sysConfigs.pageSize,
                        offset: (pn - 1) * self.$scope.sysConfigs.pageSize,
                        pagenum: pn,
                        query: qs,
                        rnd: Tools.timeStamp(),
                    };
                    dataApi[stateName](pageData)
                        .then(function(retData) {
                            if (retData.Code == 0) {
                                self.$scope.data = self.$scope.data || {};
                                self.$scope.data = angular.extend(self.$scope.data, retData.Data);
                                self.$scope.currentInfo.count = retData.Data.Count;
                                self.$scope.currentInfo.total = retData.Data.Count / self.$scope.sysConfigs.pageSize;
                                self.$scope.currentInfo.total = Math.floor(self.$scope.currentInfo.total);
                                if (retData.Data.Count % self.$scope.sysConfigs.pageSize > 0) {
                                    self.$scope.currentInfo.total++;
                                }
                                self.$scope.$broadcast("listDataLoaded", retData.Data);
                            } else {
                                Tools.alert({
                                    "icon": "error",
                                    "title": retData.Msg,
                                });
                            }
                            // $timeout(function() {
                            //     appHandle.initComponents();
                            // });
                        }, function(err) {
                            console.log(err);
                        });
                }
            },
            selectAll: function() {
                var scope = self.$scope;
                scope.data.List.forEach(function(item) {
                    if (item.Site_main != 1) {
                        item.optChecked = scope.currentInfo.checkBoxAll;
                    }
                }, this);
                // $timeout(function() {
                //     appHandle.initComponents();
                // });
            },
            deleteItem: function() {
                var scope = self.$scope;
                var itemList = [];
                scope.data.List.forEach(function(item) {
                    if (item.optChecked) {
                        itemList.push(item.Id);
                    }
                }, this);

                if (itemList.length == 0) {
                    Tools.loading("<h3>没有选择要删除的记录</h3>", 800);
                    return;
                }
                Tools.alert({
                    icon: "question",
                    title: "确认要删除 “" + itemList.length + "条” 记录吗？",
                    buttons: [{
                        name: "是",
                        className: "btn-lg btn-success",
                        click: function() {
                            var stateName = self.$scope.currentInfo.listSvrName || $state.current.name;
                            stateName = stateName + "Delete";
                            if (dataApi[stateName]) {
                                dataApi[stateName](itemList)
                                    .then(function(retData) {
                                        if (retData.Code == 0) {
                                            Tools.loading("<h3>删除成功了 " + retData.Msg + "条 记录</h3>", 800);
                                            $state.reload();
                                        } else {
                                            Tools.alert({
                                                "icon": "error",
                                                "title": retData.Msg,
                                            });
                                        }
                                        // $timeout(function() {
                                        //     appHandle.initComponents();
                                        // });
                                    });
                            }
                        },
                    }, {
                        name: "否",
                        className: "btn-lg btn-danger",
                    }],
                });
            },
            search: function(stype, qtxt) {
                var scope = self.$scope;
                if (!stype || !qtxt) {
                    Tools.loading("<h3>请输入要查询的条件</h3>", 800);
                    return;
                }
                scope.currentInfo.query = stype + ".icontains:" + qtxt;
                scope.currentInfo.currentPage = 1;
                this.listDataLoad(scope.currentInfo.currentPage, scope.currentInfo.query);
            },
            clearSearch: function() {
                var scope = self.$scope;
                scope.currentInfo.qtxt = "";
                scope.currentInfo.query = "";
                scope.currentInfo.currentPage = 1;
                this.listDataLoad(scope.currentInfo.currentPage, scope.currentInfo.query);
            },
        };
    })
    .factory("editSvr", function($rootScope, $state, $window, dataApi, Tools, Upload) {
        var $scope = {};
        var self = this;
        self.maxAttachment = 10;
        return {
            init: function(scope) {
                self.$scope = scope;
                self.$scope.editoptions = {
                    height: 200,
                    lang: "zh-CN",
                };
                self.$scope.simpleditor = {
                    height: 100,
                    toolbar: [
                        ['color', ['color']],
                        ['font', ['bold', 'underline', 'clear']],
                        ['para', ['ul', 'paragraph']],
                        ['table', ['table']],
                        ['insert', ['link']]
                    ],
                    lang: "zh-CN",
                };
            },
            getinfo: function(id) {
                var stateName = self.$scope.currentInfo.editSvrName || $state.current.name;
                stateName = stateName + "GetInfo";
                if (dataApi[stateName]) {
                    dataApi[stateName](id)
                        .then(function(retData) {
                            if (retData.Code == 0) {
                                self.$scope.data = retData.Data;
                                self.$scope.$broadcast("infoDataLoaded", retData.Data);
                            } else {
                                Tools.alert({
                                    "icon": "error",
                                    "title": retData.Msg,
                                });
                            }
                        });
                }
            },
            update: function(data) {
                if (data == null) {
                    return;
                }
                Tools.loading("<h3>正在保存数据...</h3>");
                self.$scope.saveing = true;
                var stateName = self.$scope.currentInfo.editSvrName || $state.current.name;
                if (dataApi[stateName]) {
                    dataApi[stateName](data)
                        .then(function(retData) {
                            Tools.removeLoading();
                            self.$scope.saveing = false;
                            if (retData.Code == 0) {
                                $window.history.back();
                            } else {
                                Tools.alert({
                                    "icon": "error",
                                    "title": retData.Msg,
                                });
                            }
                        }, function(err) {
                            self.$scope.saveing = false;
                        });
                }
            },
            attrSort: function() {
                if (!self.$scope.data.AttaList) {
                    return;
                }
                var list = self.$scope.data.AttaList.sort(function(a, b) {
                    return a.Sortid * 10 - b.Sortid * 10;
                });
                for (var i = 0, j = 0; i < list.length; i++) {
                    if (list[i].AttaType == -1) {
                        continue;
                    }
                    j++;
                    list[i].Sortid = j;
                }
            },
            attrUpDown: function(item, step) {
                if (!self.$scope.data.AttaList) {
                    return;
                }
                item.Sortid = item.Sortid + step;
                this.attrSort();
            },
            attrCount: function() {
                if (!self.$scope.data.AttaList) {
                    return 0;
                }
                var arr = $.grep(self.$scope.data.AttaList, function(n, i) {
                    return n.AttaType != -1;
                });
                return arr.length;
            },
            attrDelete: function(item) {
                if (!self.$scope.data.AttaList) {
                    return;
                }
                // var idx = self.$scope.data.AttaList.indexOf(item);
                // if (idx == -1) {
                //     return;
                // }
                // self.$scope.data.AttaList.splice(idx, 1);
                this.updataFileList(false, item.Attaurl);
                item.AttaType = -1;
                this.attrSort();
            },
            attaAdd: function() {
                if (this.attrCount() >= self.maxAttachment) {
                    Tools.loading("<h3>附件最多不能超过 " + self.maxAttachment + " 个</h3>", 1000);
                    return;
                }
                if (!self.$scope.data.AttaList) {
                    self.$scope.data.AttaList = [];
                    self.attrAutoId = 0;
                }
                if (!self.attrAutoId) {
                    self.attrAutoId = self.$scope.data.AttaList.length;
                }
                self.attrAutoId++;
                var attaItem = {
                    "Id": 0,
                    "Attaurl": "",
                    "Info": "附件 " + self.attrAutoId,
                    "Size": 0,
                    "Originalname": "",
                    "Sortid": self.attrAutoId,
                    "nid": self.attrAutoId,
                    "btnName": "btnAtta_" + self.attrAutoId,
                };
                self.$scope.data.AttaList.push(attaItem);
                this.attrSort();
            },
            updataFileList: function(newurl, oldurl, $file, rtype, colname) {
                if (!self.$scope.data.UpFileList) {
                    self.$scope.data.UpFileList = [];
                }
                var findFile = function(url) {
                    for (var i = 0; i < self.$scope.data.UpFileList; i++) {
                        var item = self.$scope.data.UpFileList[i];
                        if (item.FileUrl == url) {
                            return i;
                        }
                    }
                    return -1;
                }
                if (oldurl) {
                    var idx = findFile(oldurl);
                    if (idx != -1) {
                        self.$scope.data.UpFileList.splice(idx, 1);
                    }
                }
                if (newurl) {
                    var idx = findFile(oldurl);
                    if (idx != -1) {
                        return;
                    }
                    self.$scope.data.UpFileList.push({
                        FileUrl: newurl,
                        FileName: $file.name,
                        ReplaceType: rtype,
                        ColumnName: colname
                    });
                }
            },
            fileUpload: function($file, name, isEditor, upfType) {
                if (!$file) {
                    return;
                }
                console.log($file);
                var This = this;
                Tools.loading("<h3> <i class='fa fa-spinner fa-pulse fa-lg fa-fw'></i> 正在上传文件，请稍候... </h3>")
                Upload.upload({
                    url: "/api/Common/fileUpload",
                    data: {
                        file: $file,
                        uptype: upfType
                    }
                }).then(function(resp) {
                    Tools.removeLoading();
                    if (resp.data.Code == 0) {
                        var fileurl = resp.data.Data[0].url;
                        console.log(fileurl);
                        if (isEditor) { //富编辑器
                            This.updataFileList(fileurl, false, $file, 1, name);
                            $('#' + name).summernote('insertImage', fileurl, "");
                        } else if (angular.isObject(name)) {
                            //附件
                            This.updataFileList(fileurl, name.Attaurl, $file, 2, "");
                            name.Attaurl = fileurl;
                            name.FileType = "";
                            for (var i in $rootScope.sysDicts.fileType) {
                                var item = $rootScope.sysDicts.fileType[i];
                                if (!item.regexRule) {
                                    continue;
                                }
                                var regx = eval(item.regexRule);
                                if (regx.test($file.type)) {
                                    name.FileType = item.type;
                                }
                            }
                            name.Size = $file.size;
                        } else {
                            //普通上传
                            This.updataFileList(fileurl, self.$scope.data[name], $file, 3, name);
                            self.$scope.data[name] = fileurl;
                        }
                    } else {
                        Tools.alert({
                            "icon": "error",
                            "title": resp.data.Msg,
                        });
                    }
                }, function(err) {
                    Tools.removeLoading();
                    console.log(err);
                    Tools.alert({
                        "icon": "error",
                        "title": err,
                    });
                });
            },
            imagesUpload: function(files, inputId) {
                for (var i in files) {
                    if (!angular.isObject(files[i])) {
                        continue;
                    }
                    this.fileUpload(files[i], inputId, true, 0);
                }
            },
            filePreview: function(name) {
                if (angular.isString(name)) {
                    //普通文件
                    self.$scope.currentInfo.pic = self.$scope.data[name];
                } else {
                    //附件文件 
                    self.$scope.currentInfo.pic = name.Attaurl;
                }
                self.$scope.currentInfo.picShow = true;
            },
            previewClose: function() {
                self.$scope.currentInfo.pic = "";
                self.$scope.currentInfo.picShow = false;
            },
            fileClear: function(name) {
                if (angular.isString(name)) {
                    //普通文件
                    this.updataFileList(false, self.$scope.data[name]);
                    self.$scope.data[name] = "";
                } else {
                    //富文本框
                    if (name.attrs) {
                        this.updataFileList(false, name.attrs.src);
                    } else {
                        //附件文件 
                        this.updataFileList(false, name.Attaurl);
                        name.FileType = "";
                        name.Attaurl = "";
                        name.Size = 0;
                    }
                }
            },
            getDefaultStyle: function(name) {
                if ($rootScope.sysDicts[name]) {
                    for (var i in $rootScope.sysDicts[name]) {
                        var item = $rootScope.sysDicts[name][i];
                        if (item.default) {
                            return item;
                        }
                    }
                }
                return { type: "" }
            },
        };
    })
    .factory('localStorageService', [function() {
        return {
            get: function localStorageServiceGet(key, defaultValue) {
                var stored = localStorage.getItem(key);
                try {
                    stored = angular.fromJson(stored);
                } catch (error) {
                    stored = null;
                }
                if (defaultValue && stored === null) {
                    stored = defaultValue;
                }
                return stored;
            },
            update: function localStorageServiceUpdate(key, value) {
                if (value) {
                    localStorage.setItem(key, angular.toJson(value));
                }
            },
            clear: function localStorageServiceClear(key) {
                localStorage.removeItem(key);
            },
            clearAll: function() {
                localStorage.clear();
            }
        };
    }]);